package org.mokusakura.service.impl;

import org.mokusakura.domain.*;
import org.mokusakura.persistence.Util.IDWorker;
import org.mokusakura.persistence.mapper.ItemMapper;
import org.mokusakura.persistence.mapper.LineItemMapper;
import org.mokusakura.persistence.mapper.OrderMapper;
import org.mokusakura.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MokuSakura
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {
    final IDWorker idWorker = new IDWorker(2L);
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    LineItemMapper lineItemMapper;

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public Order makeOrder(Order order, User user, Cart cart) throws Exception {
        //设置默认的属性
        order.setOrderId(idWorker.nextId());
        order.setOrderDate(new Timestamp(System.currentTimeMillis()));
        order.setStatus((byte) 0);
        order.setLocale("en");
        //这个应该交由后台管理网站进行设置
        order.setCourier("");

        List<LineItem> lineItemList = new ArrayList<>(cart.getItemCartItemMap().size());
        int index = 0;
        for (CartItem cartItem : cart.getItemCartItemMap().values()) {
            LineItem lineItem = new LineItem();
            lineItem.setItemId(cartItem.getItem().getItemId())
                    .setQuantity(cartItem.getQuantity())
                    .setListPrice(cartItem.getItem().getListPrice())
                    .setLineItemNumber(index++)
                    .setOrderId(order.getOrderId());
            lineItemList.add(lineItem);
        }

        order.setLineItems(lineItemList);
        //检查存货
        for (LineItem lineItem : order.getLineItems()) {
            Integer inventoryQuantity = itemMapper.getInventoryQuantity(lineItem.getItemId());
            //库存不够
            if (inventoryQuantity.compareTo(lineItem.getQuantity()) < 0) {
                throw new Exception("Item id:" + lineItem.getItemId() + "\nInventory not enough");
            }
        }
        //检查完毕
        for (LineItem lineItem : order.getLineItems()) {
            itemMapper.updateInventoryQuantity(lineItem.getItemId(), lineItem.getQuantity());
            lineItemMapper.insertLineItem(lineItem);
        }
        orderMapper.insertOrder(order);

        return order;
    }

    public Boolean pay(Order order) throws Exception {
        //TODO 实现付款
        order.setStatus((byte) 1);
        return orderMapper.updateOrderStatus(order).equals(1);
    }

}
